package com.zggk.lzz.roadmx;


import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.district.DistrictItem;
import com.amap.api.services.district.DistrictResult;
import com.amap.api.services.district.DistrictSearch;
import com.amap.api.services.district.DistrictSearchQuery;
import com.bumptech.glide.Glide;
import com.zggk.lzz.R;
import com.zggk.lzz.mvp.MVPBaseActivity;
import com.zggk.lzz.util.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class RoadMxActivity extends MVPBaseActivity<RoadMxContract.View, RoadMxPresenter> implements RoadMxContract.View {


    @Bind(R.id.map)
    MapView mMapView;
    @Bind(R.id.back_lay)
    RelativeLayout backLay;
    @Bind(R.id.road_te)
    TextView roadTe;
    @Bind(R.id.search_layout)
    RelativeLayout searchLayout;
    @Bind(R.id.road_info_ib)
    ImageButton roadInfoIb;
    @Bind(R.id.road_skill_kpi)
    ImageButton roadSkillKpi;
    @Bind(R.id.play_image_begin)
    ImageButton playImageBegin;
    @Bind(R.id.bridge_name)
    TextView bridgeName;
    @Bind(R.id.delete)
    TextView delete;
    @Bind(R.id.halving_line)
    View halvingLine;
    @Bind(R.id.bridge_img)
    ImageView bridgeImg;
    @Bind(R.id.bridge_wz)
    TextView bridgeWz;
    @Bind(R.id.bridge_fl)
    TextView bridgeFl;
    @Bind(R.id.qc)
    TextView qc;
    @Bind(R.id.szzq_te)
    TextView szzqTe;
    @Bind(R.id.xqlz_te)
    TextView xqlzTe;
    @Bind(R.id.obvious_lay)
    RelativeLayout obviousLay;
    @Bind(R.id.disease_new_parent_layout)
    RelativeLayout diseaseNewParentLayout;
    private AMap aMap;
    private MyLocationStyle myLocationStyle;
    private double Latitude;
    private double Longitude;

    @Override
    public void onRequestError(String msg) {

    }

    @Override
    protected int getLayout() {
        return R.layout.act_road_mx;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        initView();
        initMap(savedInstanceState);
        initLan();
        initSearch();
        initData();
    }

    private void initData() {
        mPresenter.getData2(getIntent().getStringExtra("roadCode"), RoadMxActivity.this);
    }

    private void initLan() {
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
//        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);//只定位一次。
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                Latitude =  location.getLatitude();
                Longitude =  location.getLongitude();
            }
        });
    }

    private void initMap(Bundle savedInstanceState) {
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
    }

    private void initView() {
        roadTe.setText(getIntent().getStringExtra("roadName"));
        bridgeName.setText(getIntent().getStringExtra("roadName"));
        bridgeWz.setText("路线编码：" + getIntent().getStringExtra("roadCode"));
        bridgeFl.setText("起点桩号：" + Utils.getZHMCByZH(getIntent().getStringExtra("qdzh")));
        qc.setText("终点桩号：" + Utils.getZHMCByZH(getIntent().getStringExtra("zdzh")));
        szzqTe.setText("桥梁长度：" + getIntent().getStringExtra("lxcd") + "公里");
        xqlzTe.setText("路线类型：" + getIntent().getStringExtra("xmlx"));
        if (getIntent().getStringExtra("roadCode").substring(0,1).equals("Y") ){
            Glide.with(RoadMxActivity.this)
                    .load(R.drawable.xian_road_img)
                    .into(bridgeImg);
        }else if (getIntent().getStringExtra("roadCode").substring(0,1).equals("Y") ){
            Glide.with(RoadMxActivity.this)
                    .load(R.drawable.xiang_road_img)
                    .into(bridgeImg);
        }else if (getIntent().getStringExtra("roadCode").substring(0,1).equals("Y") ){
            Glide.with(RoadMxActivity.this)
                    .load(R.drawable.cun_road_img)
                    .into(bridgeImg);
        }else {
            Glide.with(RoadMxActivity.this)
                    .load(R.drawable.zhuan_road_img)
                    .into(bridgeImg);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void getDatas2(List<RoadMx2Bean> listBeans) {
        if (listBeans != null && listBeans.size() > 0) {
            final List<LatLng> points = new ArrayList<>();
            LatLngBounds.Builder b = LatLngBounds.builder();
            for (int i = 0; i < listBeans.size(); i++) {
                LatLng latLngs = new LatLng(Double.valueOf(listBeans.get(i).getLat()), Double.valueOf(listBeans.get(i).getLon()));
                points.add(latLngs);
            }
            aMap.addPolyline(new PolylineOptions().addAll(points).width(15).color(getResources().getColor(R.color.zs_color)));
            MarkerOptions markerOption = new MarkerOptions();
            markerOption.position(points.get(0));
            markerOption.draggable(true);//设置Marker可拖动
//          markerOption.icon(BitmapDescriptorFactory.fromView(getMyView1(listBeans.get(0))));
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.start2)));
            // 将Marker设置为贴地显示，可以双指下拉地图查看效果
            markerOption.setFlat(true);//设置marker平贴地图效果
            aMap.addMarker(markerOption);
            for (int i = 0; i < points.size(); i++) {
                b.include(points.get(i));
            }
            aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(b.build(), 50));
        } else {
            showToast("该路线查询不到位置信息");
        }

    }
//    //在线
//    protected View getMyView1(RoadMx2Bean pm_val) {
//        View view = LayoutInflater.from(RoadMxActivity.this).inflate(R.layout.view_infowindow1, null);
//        TextView lxbm_te = (TextView) view.findViewById(R.id.lxbm_te);
//        TextView name_te = (TextView) view.findViewById(R.id.name_te);
//        lxbm_te.setText(pm_val.get);
//        name_te.setText(pm_val);
//        return view;
//    }

    /**
     * @Description: (高亮省份)
     * @author 张成昆
     * @date 2020-4-28
     */
    private void initSearch() {
        DistrictSearch search = new DistrictSearch(RoadMxActivity.this);
        DistrictSearchQuery query = new DistrictSearchQuery();
        query.setKeywords("广东省");//传入关键字
        query.setShowBoundary(true);//是否返回边界值
        search.setQuery(query);
        search.setOnDistrictSearchListener(new DistrictSearch.OnDistrictSearchListener() {
            @Override
            public void onDistrictSearched(DistrictResult districtResult) {
                if (districtResult == null || districtResult.getDistrict() == null) {
                    return;
                }
                final DistrictItem item = districtResult.getDistrict().get(0);
                if (item == null) {
                    return;
                }
//                LatLonPoint centerLatLng = item.getCenter();//得到行政中心点坐标
//                if (centerLatLng != null) {  //地图加载时就显示行政区域
//                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(centerLatLng.getLatitude(), centerLatLng.getLongitude()), 8));//13为缩放级别
//                }
                new Thread() {
                    private PolylineOptions polylineOption;

                    public void run() {
                        String[] polyStr = item.districtBoundary();
                        if (polyStr == null || polyStr.length == 0) {
                            return;
                        }
                        for (String str : polyStr) {
                            String[] lat = str.split(";");
                            polylineOption = new PolylineOptions();
                            boolean isFirst = true;
                            LatLng firstLatLng = null;
                            for (String latstr : lat) {
                                String[] lats = latstr.split(",");
                                if (isFirst) {
                                    isFirst = false;
                                    firstLatLng = new LatLng(Double
                                            .parseDouble(lats[1]), Double
                                            .parseDouble(lats[0]));
                                }
                                polylineOption.add(new LatLng(Double
                                        .parseDouble(lats[1]), Double
                                        .parseDouble(lats[0])));
                            }
                            if (firstLatLng != null) {
                                polylineOption.add(firstLatLng);
                            }

                            polylineOption.width(7).color(getResources().getColor(R.color.bule_color));
                            Message message = handler.obtainMessage();
                            message.obj = polylineOption;
                            handler.sendMessage(message);
                        }
                    }
                }.start();
            }
        });//绑定监听器
        search.searchDistrictAnsy();//开始搜索
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            PolylineOptions polylineOption = (PolylineOptions) msg.obj;
            aMap.addPolyline(polylineOption);
        }
    };

    @OnClick({ R.id.back_lay,R.id.dw_img,R.id.delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.dw_img:
                LatLng latLng =new LatLng(Latitude,Longitude);
                aMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
                break;
            case R.id.back_lay:
                finish();
                break;
            case R.id.delete:
                finish();
                break;
        }
    }
}
